import 'package:flutter/material.dart';
import 'iconfont.dart';
import 'playgroud.dart';
import 'pages/home.dart';
import 'pages/risk_list.dart';
import 'package:safety_platform/pages/task/task_list_page.dart';
import 'package:safety_platform/pages/quick_start/page.dart';
import 'package:safety_platform/pages/notification/index.dart';
import 'package:safety_platform/pages/mine/mine_info.dart';
import 'package:safety_platform/pages/hidden_danger/page.dart';
// import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:safety_platform/models/login_user.dart';
import 'package:flutter_jpush/flutter_jpush.dart';
import 'package:safety_platform/authentication.dart';
import 'package:safety_platform/pages/message/message_list.dart';

class App extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _AppState();
  }
}

class _AppState extends State<App> with SingleTickerProviderStateMixin {
  TabController controller;
  bool isConnected = false;

  String registrationId;

  List notificationList = [];

  int _index = 0;
  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  String title = '安检通';
  @override
  void initState() {
    controller = TabController(length: 5, vsync: this);

    // controller.addListener(() {
    //   int inx = controller.index;
    //   print("当前Tab index: $inx");
    //   setState(() {
    //     title = "哈哈";
    //   });
    // });
    controller.addListener(() {
      print("ssssssssssssssssssss");
      print(controller.index);
      print(controller.indexIsChanging);
    });

    //  initPlatformState();

    _startupJpush();
    FlutterJPush.addConnectionChangeListener((bool connected) {
      setState(() {
        /// 是否连接，连接了才可以推送

        print("连接状态改变:$connected");

        this.isConnected = connected;

        if (connected) {
          FlutterJPush.getRegistrationID().then((String regId) {
            print("主动获取设备号:$regId");
            _setTags();
            setState(() {
              this.registrationId = regId;
            });
          });
        }
      });
    });

    FlutterJPush.addnetworkDidLoginListener((String registrationId) {
      _setTags();
      setState(() {
        /// 用于推送

        print("收到设备号:$registrationId");

        this.registrationId = registrationId;
      });
    });

    FlutterJPush.addReceiveNotificationListener(
        (JPushNotification notification) {
      setState(() {
        /// 收到推送

        print("收到推送提醒: $notification");

        notificationList.add(notification);
      });
    });

    FlutterJPush.addReceiveOpenNotificationListener(
        (JPushNotification notification) {
      setState(() {
        print("打开了推送提醒: $notification");

        /// 打开了推送提醒

        notificationList.add(notification);
      });
    });

    FlutterJPush.addReceiveCustomMsgListener((JPushMessage msg) {
      setState(() {
        print("收到推送消息提醒: $msg");

        /// 打开了推送提醒
        notificationList.add(msg);
      });
    });
    super.initState();
  }

  void _setTags() async {
    LoginUser user = getCurrentUser();
    if (user != null) {
      // List<String> tags = ['C${user.j}']
      // FlutterJPush.setTags(tags)
      String id = user.id.toString();
      List<String> tags = [];
      // if (user.permissions.indexOf(element))
      try {
        JPushResult result = await FlutterJPush.setAlias(id);
        if (result.isOk) {
          print('设置别名成功，Alias: ${result.result}');
        } else {
          print('设置别名失败, 失败原因: ${result.code}');
        }
      } on Exception {}
    }
  }

  void _startupJpush() async {
    print("初始化jpush");

    await FlutterJPush.startup();

    print("初始化jpush成功");
  }

  //  Future<void> initPlatformState() async {

  //   String platformVersion;
  //   print("初始化JPush");
  //    try {
  //    JPush jpush = new JPush();

  //   // Platform messages may fail, so we use a try/catch PlatformException.

  //   jpush.getRegistrationID().then((rid) {
  //     print('getRegistrationID : $rid');
  //   });

  //   jpush.setup();

  //   print("初始化JPush Done.");

  //     jpush.addEventHandler(

  //       onReceiveNotification: (Map<String, dynamic> message) async {

  //       // print("flutter onReceiveNotification: $message");

  //       // setState(() {

  //       //     _platformVersion = "flutter onReceiveNotification: $message";

  //       //   });

  //     },

  //     onOpenNotification: (Map<String, dynamic> message) async {

  //       print("flutter onOpenNotification: $message");

  //       setState(() {

  //           // debugLable = "flutter onOpenNotification: $message";

  //         });

  //     },

  //     onReceiveMessage: (Map<String, dynamic> message) async {

  //       print("flutter onReceiveMessage: $message");

  //     },

  //     );

  //   } on Exception {

  //     platformVersion = 'Failed to get platform version.';
  //     print(platformVersion);
  //     print('为什么你不行了啊.');

  //   }

  //   // If the widget was removed from the tree while the asynchronous platform

  //   // message was in flight, we want to discard the reply rather than calling

  //   // setState to update our non-existent appearance.

  //   if (!mounted) return;

  //   // setState(() {

  //   //   debugLable = platformVersion;

  //   // });

  // }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        routes: {
          'todayPlan': (_) => TaskListPage(),
          'received_notification_list': (_) => NotificationPage(),
        },
        theme: ThemeData(
          // scaffoldBackgroundColor: Color.fromARGB(255, 27, 130, 210),
          backgroundColor: Color.fromARGB(251, 241,241,241),

          textTheme: TextTheme(
              body2: TextStyle(
                color: Colors.red,
                fontSize: 14,
              ),
              subhead: TextStyle(
                fontSize: 14,
                // color: Colors.grey,
              )),
          // This is the theme of your application.
          //
          // Try running your application with "flutter run". You'll see the
          // application has a blue toolbar. Then, without quitting the app, try
          // changing the primarySwatch below to Colors.green and then invoke
          // "hot reload" (press "r" in the console where you ran "flutter run",
          // or simply save your changes to "hot reload" in a Flutter IDE).
          // Notice that the counter didn't reset back to zero; the application
          // is not restarted.
          // textTheme: TextTheme(),

          primaryColor: Color.fromARGB(255, 27, 130, 210),
          primarySwatch: Colors.blue,
        ),
        home: Scaffold(
            // appBar: AppBar(
            //   title: new Text(title),
            //   elevation: 0,
            //   backgroundColor: Color.fromARGB(255, 27, 130, 210),
            //   centerTitle: true, //设置标题是否局中
            // ),
            body: new TabBarView(
              controller: controller,
              children: <Widget>[
                new Home(),
                new NotificationPage(),
                new QuickStart(),
                new MessageListPage(),
                new MineInfoPage(),
                // new Playground(parentContext: context,),
              ],
            ),
            bottomNavigationBar: new Material(
              color: Colors.white,
              child: TabBar(
                labelColor: Colors.blue,
                controller: controller,
                unselectedLabelColor: Colors.grey,
                tabs: <Widget>[
                  Tab(
                    text: '首页',
                    icon: Icon(MyIconFont.shu),
                  ),
                  Tab(
                    text: '文书',
                    icon: Icon(MyIconFont.shu),
                  ),
                  Tab(
                    text: '检查',
                    icon: Icon(MyIconFont.yinhuanjiancha),
                  ),
                  Tab(
                    text: '聊天',
                    icon: Icon(MyIconFont.zhibiaozhushibiaozhu),
                  ),
                  Tab(
                    text: '我的',
                    icon: Icon(MyIconFont.wode1),
                  ),
                ],
              ),
            )));
  }
}
